<?php

namespace app\admin\controller;

use app\common\model\Area;
use app\common\model\ServiceImage;
use app\common\model\ServiceMiddle;
use app\common\model\ServiceTeam;
use app\common\model\ServiceType;

class Service extends Base
{
    public function __construct()
    {
        parent::__construct();
        $this->isLogin();
    }


    /**
     * @route('service/servicetypelist')
     * 服务分类列表
     */
    public function ServiceTypeList()
    {
        $Model = new ServiceType();

        $get['type_name'] = input('get.type_name');
        $get['status'] = input('get.status');

        $rs_data = $Model->get_list_page($get,'sort asc','*',$this->limit);

        $tvar = array(
            "title" => "服务分类列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
            "isHqAdmin" => $this->isHqAdmin()
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('service/type/servicetypelist');
    }


    /**
     * @route('service/boxeservicetype')
     * 编辑分类
     */
    public function BoxeServiceType()
    {
        $Model = new ServiceType();

        if(request()->isAjax()){
            $type_id = $this->regpost('type_id','int','0');
            $params['type_name'] = $this->regpost('type_name','string');
            $params['sort'] = $this->regpost('sort','int');
            $params['status'] = $this->regpost('status','int');

            $rs = $Model->edit($params, $type_id);
            if($rs === false){
                $this->error($Model->getError());
            }
            $this->success('操作成功','/service/servicetypelist');
        }

        $type_id = input('get.type_id',0);
        $data = null;
        if($type_id != 0){
            $data = $Model->getOne(['type_id' => $type_id],'*');
        }


        $tvar = [
            'time' => time(),
            'title' => '编辑分类'
        ];
        $this->assign("data", $tvar);
        $this->assign("type", $data);
        return $this->fetch('service/type/boxeservicetype');
    }

    /**
     * @route('service/delservicetype')
     * 删除分类
     */
    public function DelServiceType()
    {
        $type_id = input('get.type_id');
        if($type_id > 0){
            $rs = ServiceType::destroy($type_id);
            if($rs === false){
                $this->error('操作失败');
            }
            $this->success('操作成功');
        }
    }


    /**
     * @route('service/servicelist')
     * 服务 列表
     */
    public function ServiceList()
    {
        $Model = new \app\common\model\Service();

        $get['service_name'] = input('get.service_name');
        $get['status'] = input('get.status');

        $get['shop_id'] = $this->_shopid;
//        if($get['shop_id'] != 0){
//            $get['approveds'] = "2,3";
//        }

        $field = "a.*,b.type_name,c.shop_name";

        if($this->_shopid == 0){
            $orderby =  "a.shop_id asc, a.approved asc";
        }else{
            $orderby = "a.approved asc, a.sort asc";
        }


        $rs_data = $Model->get_list_page($get,$orderby,$field,$this->limit);

        $tvar = array(
            "title" => "服务列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
            "isHqAdmin" => $this->isHqAdmin()
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('service/servicelist');
    }


    /**
     * @route('service/boxeservice')
     * 编辑服务
     */
    public function BoxeService()
    {
        $Model = new \app\common\model\Service();
        $TypeModel = new ServiceType();

        if(request()->isAjax()){

            $params = input();

            $validate = new \app\admin\validate\Service();

            $res = $validate->scene('EditService')->check($params);
            if(!$res){
                $this->error($validate->getError());
            }

            $service_id = $params['service_id'];

            $service = [
                'shop_id'   => $this->_shopid,
                'type_id'   => $params['type_id'],
                'service_name'  => $params['service_name'],
                'content'  => $params['content'],
                'price'  => $params['price'],
                'sale_price'  => $params['sale_price'],
                'top_pic'  => $params['top_pic'],
                'sort'  => $params['sort'],
                'status'  => $params['status'],
                'summary'  => $params['summary'],
            ] ;
            // 总部添加服务无需审核
            $service['approved'] =1;
            if($this->_shopid == 0){
                $service['approved'] = 2;
            }

            $rs = $Model->edit($service,$service_id);
            if($rs === false){
                $this->error($Model->getError());
            }
            $this->success('操作成功','/service/servicelist');
        }

        $Id = input('get.service_id',0);
        $data = null;
        if($Id != 0){
            $data = $Model->getOne(['service_id' => $Id],'*');
        }

        $cond['status'] =1;
        $type_list = $TypeModel->get_list($cond,'sort asc','type_id, type_name');

        $tvar = [
            'typelist' => $type_list,
            'time' => time(),
            'title' => '编辑服务'
        ];
        $this->assign("data", $tvar);
        $this->assign("service", $data);
        return $this->fetch('service/boxeservice');
    }

    /**
     * @route('service/delservice')
     * 删除服务
     */
    public function DelService()
    {
        $ID = input('get.service_id');
        if($ID > 0){
            $rs = \app\common\model\Service::destroy($ID);
            if($rs === false){
                $this->error('操作失败');
            }
            $this->success('操作成功');
        }
    }

    /**
     * @route('service/failservice')
     * 审核不通过的原因
     */
    public function FailService()
    {
        $ID = input('get.service_id');
        $Model = new \app\common\model\Service();

        $data = $Model->getOne(['service_id' => $ID],'reasons');

        $tvar = array(
            "title" => "审核意见",
            "time"  => time(),
            "data"  => $data
        );

        $this->assign("data", $tvar);
        return $this->fetch('service/failservice');
    }


    // 服务团队管理模块
    /**
     * 服务团队管理列表
     * @route('service/teamlist')
     */
    public function TeamList()
    {
        $Model = new \app\common\model\ServiceTeam();
        $get['team_name'] = input('get.team_name');
        $get['status'] = input('get.status');

        $get['shop_id'] = $this->_shopid;

        $field = "a.*,b.shop_name";

        if($this->_shopid == 0){
            $orderby =  "";
        }else{
            $orderby = "a.sort asc";
        }

        $rs_data = $Model->get_list_page($get,'a.shop_id asc, a.sort asc',$field,$this->limit);

        $tvar = array(
            "title" => "服务团队列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
            "isHqAdmin" => $this->isHqAdmin()
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('service/team/teamlist');
    }


    /**
     * @route('service/boxeteam')
     * 编辑服务团队
     */
    public function BoxeTeam()
    {
        $Model = new \app\common\model\ServiceTeam();
        $AreaModel = new Area();


        if(request()->isAjax()){

            $params = input();

            // 验证器
            $validate = new \app\admin\validate\ServiceTeam();
            $res = $validate->scene('EditServiceTeam')->check($params);
            if(!$res){
                $this->error($validate->getError());
            }

            $Id = $params['team_id'];

            $team = [
                'shop_id'   => $this->_shopid,
                'province_id'   => $params['province_id'],
                'city_id'   => $params['city_id'],
                'area_id'  => $params['area_id'],
                'street_id'  => $params['street_id'],
                'team_name'  => $params['team_name'],
                'phone'  => $params['phone'],
                'description'  => $params['description'],
                'top_pic'  => $params['top_pic'],
                'sort'  => $params['sort'],
                'status'  => $params['status'],
                'province_name' => $AreaModel->getOne(['id' => $params['province_id']],'name')['name'],
                'city_name' => $AreaModel->getOne(['id' => $params['city_id']],'name')['name'],
                'area_name' => $AreaModel->getOne(['id' => $params['area_id']],'name')['name'],
                'street_name' => $AreaModel->getOne(['id' => $params['street_id']],'name')['name'],
            ];

            $rs = $Model->edit($team,$Id);
            if($rs === false){
                $this->error($Model->getError());
            }
            $this->success('操作成功','/service/teamlist');
        }

        $Id = input('get.team_id',0);
        $data = null;
        if($Id != 0){
            $data = $Model->getOne(['team_id' => $Id],'*');
//市
            if($data['city_id']){
                $Citylists = $AreaModel->get_list(array("pid" => $data['province_id']),'id,name');
            }else{
                $Citylists = $AreaModel->get_list(array("level" => 2),'id,name');
            }
            //区/县
            if($data['area_id']){
                $Arealists = $AreaModel->get_list(array("pid" => $data['city_id']),'id,name');
            }else{
                $Arealists = $AreaModel->get_list(array("level" => 3),'id,name');
            }
            // 街道
            if($data['street_id']){
                $Streetlists = $AreaModel->get_list(array("pid" => $data['area_id']),'id,name');
            }else{
                $Streetlists = $AreaModel->get_list(array("level" => 4),'id,name');
            }

        }else{
            //市
            $Citylists = array();
            //区/县
            $Arealists = array();
            // 街道
            $Streetlists = array();
        }

        // 获取省会地区名称
        $cond['level'] = 1;
        $province = $AreaModel->get_list($cond,'id,name');

        $tvar = [
            'time' => time(),
            'title' => '编辑团队',
            "province" => $province,
            "city"  => $Citylists,
            "area"  => $Arealists,
            "street"    => $Streetlists
        ];
        $this->assign("data", $tvar);
        $this->assign("team", $data);
        return $this->fetch('service/team/boxeteam');
    }


    /**
     * @route('service/delteam')
     * 删除服务团队
     */
    public function DelTeam()
    {
        $ID = input('get.team_id');
        if($ID > 0){
            $rs = \app\common\model\ServiceTeam::destroy($ID);
            if($rs === false){
                $this->error('操作失败');
            }
            $this->success('操作成功');
        }
    }


    /**
     * @route('service/sendsinglelist')
     * 派单列表
     */
    public function SendSingleList()
    {
        $ServerMiddle = new ServiceMiddle();

        $get = null;
        $get['service_name'] = input('get.service_name');
        $get['state'] = input('get.state');

        $field = "a.*,b.pay_status,b.orderno,b.pay_time,c.service_name,c.sale_price,d.shop_name,e.name as real_name,e.phone as user_phone,e.province_name,e.city_name,e.area_name,e.area_name,e.street_name,e.detail,f.team_name,f.phone as team_phone";

        $get['shop_id'] = $this->_shopid;

        $rs_data = $ServerMiddle->get_list_page($get,'a.state asc',$field,$this->limit);

        $tvar = array(
            "title" => "派单列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
            "isHqAdmin" => $this->isHqAdmin()
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('service/middle/middlelist');
    }

    /**
     * @route('service/sendsing')
     * 派单
     */
    public function SendSing()
    {
        $ServerMiddle = new ServiceMiddle();
        $teamModel = new ServiceTeam();

        $send_id = input('send_id');
        if(!$send_id){
            $this->error('请提交正确参数');
        }
        if(input('handle') == "ajax"){
            $teamId = input('team');

            $team_data = $teamModel->getOne(['team_id' => $teamId],'team_name');
            if($team_data){
                $update['team_id'] = $teamId;
                $update['state'] = 2;
            }

            $rs = $ServerMiddle->edit($update,$send_id);
            if($rs === false){
                $this->error($ServerMiddle->getError());
            }
            $this->success('操作成功','/service/sendsinglelist');

        }
        $send = $ServerMiddle->getLeftOne(['send_id' => $send_id],'a.send_id,c.area_id,c.province_name,c.city_name,c.area_name,c.street_name,c.detail');

        $cond['status'] = 1;
        if($this->_shopid){
            $cond['shop_id'] = $this->_shopid;
        }
        $cond['area_id'] = $send['area_id'];
        $teamList = $teamModel->get_list_page($cond,'a.shop_id asc,a.sort asc','a.team_id,a.team_name','1000','','2');


        $tvar = [
            'time' => time(),
            'title' => '派单',
            "send" => $send,
            "teamlist"  => $teamList,
        ];
        $this->assign("data", $tvar);
        return $this->fetch('service/middle/boxesend');
    }



    /**
     * @route('service/serviceimage')
     * 商品图库列表
     */
    public function serviceimage()
    {
        $get['service_id'] = input('get.service_id');
        $model = new \app\common\model\Service();
        $imageModel = new ServiceImage();
        $where['p.service_id'] = $get['service_id'];
        $where['p.is_del'] = 1;
        $isdisplay = true;
        if($this->_shopid != 0){
            $isdisplay = false;
            $where['p.shop_id'] = $this->_shopid;
        }
        $product = $model
            ->alias('p')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->where($where)
            ->field('p.*,s.shop_name')
//            ->buildSql();
            ->find();
//        var_dump($product->toArray());die;
        if(empty($product)){
            $this->error('不存在该服务','/service/servicelist');
        }
        $rs_data = $imageModel->where('service_id','=',$get['service_id'])->order('sort', 'asc')->paginate($this->limit);
//        var_dump(123);die;
        $tvar = array(
            "title" => "服务图库列表",
            "time"  => time(),
            "images"  => $rs_data,
            "get"   => $get,
            "isdisplay" => $isdisplay,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign("product", $product->toArray());
        $this->assign('page', $page);
        return $this->fetch('service/serviceimage');
    }

    /**
     * @route('service/showimage')
     * 商品图片显示隐藏
     */
    public function ShowImage()
    {
        $imageid = input('imageid');
        $model = new ServiceImage();
        $where['image_id'] = $imageid;
        if($this->_shopid != 0){
            $where['p.shop_id'] = $this->_shopid;
        }
        $image = $model
            ->alias('i')
            ->leftJoin('ddt_service p','i.service_id = p.service_id')
            ->where($where)
            ->field('i.*')
            ->find();
//        var_dump($stock);die;
        if(!$image){
            $this->error('不存在该图片');
        }
        $data = $image->toArray();
        if($data['is_show'] == 0){
            $param['is_show'] = 1;
        } else {
            $param['is_show'] = 0;
        }
        $rs2 = $model->edit($param,$imageid);
        if($rs2 === false){
            $this->error("操作失败");
        }
        $this->success('操作成功');
    }

    /**
     * @route('service/boxeimage')
     * 添加编辑商品图库
     */
    public function BoxeImage()
    {
        $model = new ServiceImage();
        $pmodel = new \app\common\model\Service();

        if(input('handle') == "upload"){
            $res = \Upload::FileUpload('file','serviceimages',1024*1024*10,'jpeg,png,jpg,gif');
            if(!$res['data']){
                $this->result([],-1,$res['msg']);
            }
            $this->result($res['data']['file_path'],1);
        }

        $get['image_id'] = input('get.image_id');
        $get['service_id'] = input('get.service_id');
        if(request()->isAjax()){
            $image_id = $this->regpost("image_id","int",0);
            $service_id = $this->regpost("service_id","int");
            $is_show = input('is_show');
            if($is_show != 0 && $is_show != 1){
                $this->error('参数有误');
            }
            if($image_id != 0){
                $image = $model->where('image_id','=',$image_id)->find();
                if(!$image){
                    $this->error('不存在的商品图片','/service/serviceimage?service_id='.$service_id);
                }
            }
            $where['service_id'] = $service_id;
            $where['is_del'] = 1;
            if($this->_shopid != 0){
                $where['shop_id'] = $this->_shopid;
            }
            $product = $pmodel->where($where)->find();
            if(!$product){
                $this->error('不存在该服务','/service/servicelist');
            }
            $getdata = $product->toArray();
            $data['service_id'] = $getdata['service_id'];
////            var_dump(123);die;
            $data['url'] = $this->regpost("imageurl","string");
            $data['sort'] = $this->regpost("sort","int");
            $data['is_show'] = $is_show;
//            var_dump($data);die;
            $model->startTrans();
            $rs = $model->edit($data,$image_id);
            if($rs === false){
                $model->rollback();
                $this->error($model->getError());
            }
            if($this->_shopid != 0) {
                $result = $pmodel->edit(array("approved"=>1),$service_id);
                if($result === false){
                    $model->rollback();
                    $this->error($pmodel->getError());
                }
            }
            $model->commit();
            $this->success('操作成功','/service/serviceimage?service_id='.$service_id);
        }
        $image = null;
        if($get['image_id'] != 0){
            $image = $model->where('image_id','=',$get['image_id'])->find();
        }
//        var_dump($checkdetail);
        $tvar = array(
            "title" => "添加商品图片",
            "time"  => time(),
            "image_id" => $get['image_id'],
            "service_id" => $get['service_id'],
        );
//        var_dump($get['stock_id']);die;
        if($get['image_id'] != 0){
            $tvar['title'] = "编辑商品图片";
        }
        $this->assign("data", $tvar);
        $this->assign("images", $image);
        return $this->fetch('service/boxeimage');
    }




}